package com.belazy.library.web.util;

import lombok.Builder;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.jetbrains.annotations.Nullable;

import java.util.Iterator;
import java.util.Map;


/**
 * @Description <p> OkHttpUtil工具类 </p>
 * @Author chupeng.tang
 * @CreateTime 2023/5/19 17:29
 * @Version 1.0
 */
@Slf4j
@Builder
public class OkHttpUtil {
    private OkHttpClient okHttpClient;

    @Nullable
    private String buildResult(Request request) {
        Response response = null;
        try {
            response = okHttpClient.newCall (request).execute ();
            log.info ("Response=>{}",response);
            if(null == response){
                return null;
            }
            if(response.code ()==200 || response.code ()==400 || response.code ()==500){
                ResponseBody responseBody = response.body ();
                log.info ("ResponseBody=>{}", responseBody);
                if(null!=responseBody){
                    return responseBody.string ();
                }
            }
        } catch (Exception e) {
            log.error ("okhttp3 post error >> ex = {}", e);
        } finally {
            if (response != null) {
                response.close ();
            }
        }
        return null;
    }

    /**
     * get
     *
     * @param url     请求的url
     * @param queries 请求的参数，在浏览器？后面的数据，没有可以传null
     * @return
     */
    public String get(String url, Map<String, String> queries) {
        StringBuffer sb = new StringBuffer (url);
        if (queries != null && queries.keySet ().size () > 0) {
            boolean firstFlag = true;
            Iterator iterator = queries.entrySet ().iterator ();
            while (iterator.hasNext ()) {
                Map.Entry entry = (Map.Entry<String, String>) iterator.next ();
                if (firstFlag) {
                    sb.append ("?" + entry.getKey () + "=" + entry.getValue ());
                    firstFlag = false;
                } else {
                    sb.append ("&" + entry.getKey () + "=" + entry.getValue ());
                }
            }
        }
        Request request = new Request.Builder ().url (sb.toString ()).build ();
        return buildResult (request);
    }


    /**
     * post
     *
     * @param url    请求的url
     * @param params post form 提交的参数
     * @return
     */
    public String post(String url, Map<String, String> params) {
        FormBody.Builder builder = new FormBody.Builder ();
        //添加参数
        if (params != null && params.keySet ().size () > 0) {
            for (String key : params.keySet ()) {
                builder.add (key, params.get (key));
            }
        }
        Request request = new Request.Builder ()
                .url (url)
                .post (builder.build ())
                .build ();
        return buildResult (request);
    }

    /**
     * Post请求发送JSON数据....{"name":"zhangsan","pwd":"123456"}
     * 参数一：请求Url
     * 参数二：请求的JSON
     * 参数三：请求回调
     */
    public String postJsonParams(String url, String jsonParams) {
        RequestBody requestBody = RequestBody.create (jsonParams,MediaType.parse ("application/json; charset=utf-8"));
        Request request = new Request.Builder ()
                .url (url)
                .post (requestBody)
                .build ();
        return buildResult (request);
    }

    /**
     * Post请求发送xml数据....
     * 参数一：请求Url
     * 参数二：请求的xmlString
     * 参数三：请求回调
     */
    public String postXmlParams(String url, String xml) {
        RequestBody requestBody = RequestBody.create (xml,MediaType.parse ("application/xml; charset=utf-8"));
        Request request = new Request.Builder ()
                .url (url)
                .post (requestBody)
                .build ();
        return buildResult (request);
    }
}
